package tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * Created with IntelliJ IDEA.
 * Description: 107. 二叉树的层序遍历 II
 * User: Li_yizYa
 * Date: 2025/5/25
 * Time: 22:06
 */
public class Solution5 {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int len = queue.size();
            List<Integer> tmp = new ArrayList<>();
            while (len > 0) {
                TreeNode node = queue.poll();
                tmp.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
            ret.add(tmp);
        }
        int right = ret.size() - 1;
        int left = 0;
        while (left < right) {
            List<Integer> tmp = ret.get(left);
            ret.set(left, ret.get(right));
            ret.set(right, tmp);
            left++;
            right--;
        }
        return ret;
    }
}
